package controller

import (
	"GoAdmin/common"
	"GoAdmin/models"
	"GoAdmin/utils"
	"log"
	"net/http"

	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"xorm.io/builder"
)

const JwtSecret = "rn13jUwFP2pYFzq2ORVD"

func Login(c *gin.Context) {
	log.Println(c.PostForm("username"))
	log.Println(c.PostForm("password"))
	userName := c.PostForm("username")
	password := c.PostForm("password")
	valid := validation.Validation{}
	valid.Required(userName, "username").Message("请输入用户名")
	valid.Required(password, "password").Message("请输入密码")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	} else {
		condition := builder.NewCond()
		condition = condition.And(builder.Eq{"name": userName, "password": utils.Md5(password)})

		oaUsers, ok, err := new(models.OaUser).GetUserByCondition(condition)
		if !ok || err != nil {
			log.Println(ok, err)
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "用户名或秘密不正确", "data": nil})
			return
		}
		token, _ := common.CreateToken(oaUsers)
		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "ok", "data": gin.H{"id": oaUsers.Id, "name": oaUsers.Name, "token": token}})
		return
	}
}
